package com.wuge.auth.controller;


import com.alibaba.fastjson.TypeReference;
import com.wuge.auth.feign.MemberFeign;
import com.wuge.auth.vo.UserLoginVo;
import com.wuge.common.to.MemberTo;
import com.wuge.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @Resource
    private MemberFeign memberFeign;
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("login.html")
    public String validate(HttpSession httpSession){
        Object loginUser = httpSession.getAttribute("loginUser");
        if (loginUser==null){
            return "login";
        }
        else {
            return "redirect:http://gulimall.com";
        }
    }
    @RequestMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession httpSession){
        R login = memberFeign.login(userLoginVo);
        if (login.getCode()!=0){
            Map map=new HashMap();
            map.put("msg",login.get("msg"));
            redirectAttributes.addFlashAttribute("errors",map);
            return  "redirect:http://auth.gulimall.com/login.html";
        }
        MemberTo data = login.getData(new TypeReference<MemberTo>() {

        });
         httpSession.setAttribute("loginUser",data);
        return "redirect:http://gulimall.com";
    }
}
